﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web.UI;
using System.Threading;

using TimKen.DataEntity;
using TimKen.DataAccess;
using TimKen.BussLogic;
using System.Text.RegularExpressions;
using Microsoft.Security.Application;
using System.Web;
using System.Globalization;
using System.Xml;
using System.IO;
using System.Data;
using System.Collections;
namespace TimKen.App
{
    /// <summary>
    /// 前台程序页面的基类
    /// </summary>
    public class WebPage : Page
    {
        /// <summary>
        /// Gets if the url is secure or not
        /// </summary>
        public static bool isSecureURL
        {
            get
            {
                // Check the request     
                if (HttpContext.Current.Request.IsSecureConnection
                    || (HttpContext.Current.Request.ServerVariables["HTTPS"] != null &&
                        HttpContext.Current.Request.ServerVariables["HTTPS"].ToLower() == "on"))
                    return true;
                if ((!string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString())) &&
                    (HttpContext.Current.Request.ServerVariables["HTTP_HOST"].ToString().EndsWith("443")))
                    return true; // url is not secure:       
                return false;
            }
        }



        public string GetLangString(string key)
        {
            return TimKen.Localization.LocalizationUtility.GetText(key);
        }

        public int LanguageID
        {
            get
            {
                switch (Thread.CurrentThread.CurrentUICulture.ToString())
                {
                    case "zh-CN":
                        return 1;
                    case "en-US":
                        return 2;
                    default:
                        return 1;
                }
            }
        }
        protected string sValidMessage = "";
        public string ValidMessage
        {
            get
            {
                return this.sValidMessage;
            }
            set
            {
                this.sValidMessage = value;
            }
        }

        public string LanguageWhereStr
        {
            get { return " LanguageID=" + LanguageID; }
        }
        public ShopCartSet ShopCart
        {
            get
            {
                if (Session["ShopCartSet"] == null)
                {
                    Session["ShopCartSet"] = new ShopCartSet();
                }
                return (ShopCartSet)Session["ShopCartSet"];

            }
            set
            {
                Session["ShopCartSet"] = value;
            }
        }
        /// <summary>
        /// 上传文件相对路径
        /// </summary>
        public string UploadFilePath
        {
            get { return "/upload/"; }
        }



        public const string ResourcePath = "\\upload\\resource\\";

        public const string UploadFilePathForUser = "/upload/user/";
        public const string UploadFilePathForProduct = "/upload/product/";
        public const string UploadFilePathForCulture = "/Common/Image/common/culture/";
        public const string UploadFilePathForResource = "/upload/resource/";

        /// <summary>
        /// 上传文件物理路径
        /// </summary>
        public string PhysicalUploadFilePath
        {
            get { return Server.MapPath(UploadFilePath); }
        }



        public string PhysicalUploadFilePathForUser
        {
            get
            {
                return Server.MapPath(UploadFilePathForUser);
            }
        }


        public string PhysicalUploadFilePathForProduct
        {
            get
            {
                return Server.MapPath(UploadFilePathForProduct);
            }
        }




        /// <summary>
        /// 获取Bool值的图片
        /// </summary>
        /// <returns></returns>
        public string GetBoolPic(bool IsTrue)
        {
            string boolImg = "<img src='../../Admin/Images/{0}' title='{1}' alt='{1}'>";
            return IsTrue
                       ? string.Format(boolImg, "yes.gif", GetLangString("Yes"))
                       : string.Format(boolImg, "no.gif", GetLangString("No"));
        }


        public string CurrentUserName
        {
            get { return Session["User"] == null ? null : ((UserS) Session["User"]).UserName; }
        }

      
        //TimKen.BussLogic.UserAccountManager uam = new UserAccountManager();



        /// <summary>
        /// 当前页面所允许访问的角色id都好隔开的列表。如1,2,3,4,7
        /// </summary>
        public string PageAllowRoles = "";

        /// <summary>
        /// 在前台通过js弹出消息窗口,确定后跳转到主页面
        /// </summary>
        /// <param name="msg">弹出消息</param>
        /// <param name="url">跳转页面url</param>
        protected void Alert(string msg, string url)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "ok",
                                               "<script>alert(\"" + msg + "\");window.location.href='" + url +
                                               "';</script>");
        }

        //public string GetOptionType(string fieldType)
        //{
        //    switch (fieldType)
        //    {
        //        case "0": return GetLangString("FieldType_TextBox");
        //        case "1": return GetLangString("FieldType_TextArea");
        //        case "2": return GetLangString("FieldType_Select");
        //        default: return GetLangString("FieldType_TextBox");
        //    }
        //}

        /// <summary>
        /// 在前台通过js弹出消息窗口
        /// </summary>
        /// <param name="msg">弹出消息</param>
        protected void Alert(string msg)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "ok", "<script>alert(\"" + msg + "\");</script>");
        }

        protected void Alert2(string msg, string url)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "ok",
                                               "<script>alert(\"" + msg + "\");</script>");
        }



        /// <summary>
        /// 根据品牌ID获取品牌名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetBrandName(object id)
        {
            if (!TypeParse.IsNumeric(id))
                return "";

            int brandId = Convert.ToInt32(id);

            string sql = "SELECT  Name FROM  PBrand WHERE BrandID=" + brandId;
            object brandName = DbHelperSQL.GetSingle(sql);

            if (brandName == null)
                return "";

            return brandName.ToString();
        }

        /// <summary>
        /// 获取多语言的单位
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetUnit(string UnitEn)
        {
            string sql = "SELECT BaseUnitDesc  FROM BaseUnit WHERE BaseUnit='{0}' AND LanguageID={1}";
            sql = string.Format(sql, UnitEn, LanguageID);
            object Unit = DbHelperSQL.GetSingle(sql);

            if (Unit == null)
                return "";

            return Unit.ToString();
        }





        /// <summary>
        /// 根据产品类型ID获取产品类型名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetCategoryName(object id)
        {
            if (!TypeParse.IsNumeric(id))
                return "";

            int categoryId = Convert.ToInt32(id);
            PCategoryManager categoryManager = new PCategoryManager();


            PCategory catetory = categoryManager.GetModel(categoryId, (LanguageEnum) LanguageID);

            if (catetory == null)
                return "";
            return catetory.CategoryName;
        }

 


        


        protected override void OnError(EventArgs e)
        {
            //base.OnError(e);

            //Response.Redirect("/Error.aspx");
        }


        public UserType CurrentUserType
        {
            get
            {
                //if (string.IsNullOrEmpty(CurrentUserName))
                //    return UserType.Viewer;

                //WebUserManager wum = new WebUserManager();
                //if (wum.GetModel(CurrentUserName) != null)
                //    return UserType.SelfRegistered;

                //UserAccountManager uam = new UserAccountManager();

                //UserAccount user = uam.GetModel(CurrentUserName);

                //if (user != null && user.RoleID == 3)
                //    return UserType.FactoryBuyer;

                if (Session["User"] != null)
                {
                    UserS u = Session["User"] as UserS;
                    return u.UserType;
                }

                return UserType.Viewer;
            }
        }


        public UserS CurrentUser {
            get
            {
                if (
                    Session["User"] != null)
                {
                    UserS u = Session["User"] as UserS;
                    return u;
                }
                return null;
            }
        }

        private UserType AllowUserType { get; set; }

        //public  virtual  bool AllowVisit {

        //    get {
        //        if (AllowUserType != 0) 
        //        {
        //            return (AllowUserType == (AllowUserType | CurrentUserType));
        //        }
        //        return true; //默认返回有权访问
        //    }
        //}

        internal Dictionary<string, UserType> pageAllowUserType = new Dictionary<string, UserType>();


        protected void SetLanguage(string language)
        {
            HttpCookie cookie = new HttpCookie("Language");
            DateTime dt = DateTime.Now;//定义时间对象
            TimeSpan ts = new TimeSpan(0, 20, 0);
            cookie.Expires.Add(ts);
            cookie.Value = language;
            HttpContext.Current.Response.AppendCookie(cookie);
            CultureInfo culture = new CultureInfo(language);
            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;
        }


        protected override void InitializeCulture()
        {

            if (Session["lan"] != null)
                SetLanguage(Session["lan"].ToString());
            //if (!string.IsNullOrEmpty(Request.QueryString["lan"]) && Request.QueryString["lan"] == "en")
            //    SetLanguage("en-US");
            //if (!string.IsNullOrEmpty(Request.QueryString["lan"]) && Request.QueryString["lan"] == "cn")
            //    SetLanguage("zh-CN");

            base.InitializeCulture();
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            //权限控制
            if (Cache["PageAllowUserType"] == null)
            {
                Cache["PageAllowUserType"] = InitPageAuthorization(pageAllowUserType);
            }
            pageAllowUserType = Cache["PageAllowUserType"] as Dictionary<string, UserType>;
            if (pageAllowUserType != null)
            {
                string page = Request.Url.LocalPath.ToLower();
                if (pageAllowUserType.ContainsKey(page))
                {
                    //如果用户尚未登陆,则跳转到登陆界面
                    if (CurrentUserType == UserType.Viewer)
                        Response.Redirect("/User/Login.aspx", true);


                    AllowUserType = pageAllowUserType[page];
                    if (AllowUserType != (AllowUserType | CurrentUserType))
                    {
                       if(page == "/order/checkaccount.aspx")
                            Response.Redirect("/Error.aspx?flag=1");

                       else if (CurrentUserType != UserType.FactoryFinance)
                           Response.Redirect("/ErrorAuthority.aspx?reurl=" + AntiXss.UrlEncode(Request.Url.ToString()), true);
                        else
                        {
                            Response.Redirect("/Error.aspx");
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException("Page Authorization File FirstBridge");
            }

 

        }

        private Dictionary<string, UserType> InitPageAuthorization(Dictionary<string, UserType> list)
        {
            //权限设置，此处的链接全部为小写字母！！
            list.Add("/order/ordership.aspx", UserType.FactoryBuyer);
            list.Add("/order/checkaccount.aspx", UserType.FactoryFinance);
            list.Add("/user/inbox.aspx", UserType.FactoryBuyer | UserType.FactoryFinance);
            list.Add("/user/messageview.aspx", UserType.FactoryBuyer | UserType.FactoryFinance);
            list.Add("/order/orderlist.aspx", UserType.FactoryBuyer);
            list.Add("/user/edit.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);
            list.Add("/cart/view.aspx", UserType.FactoryBuyer);


            list.Add("/favorite/favoriteview.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            //list.Add("/product/productlist.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            //list.Add("/product/poptionlistsearch.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            //list.Add("/product/productinfo.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            //list.Add("/resource/resourcelist.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            //list.Add("/product/promotion.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);

            list.Add("/services/training.aspx", UserType.FactoryBuyer | UserType.SelfRegistered | UserType.FactoryFinance);
            return list;
        }

        #region 注释的代码
        /// <summary>
        /// 通过订单状态位获取状态描述
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        //[Obsolete("多语言问题没有处理已经建立OrderStatus表")]
        //public string GetOrderStatusDesc(object o)
        //{
        //    int status = Convert.ToInt32(o);

        //    OrderStatus OrderStatus = (OrderStatus)status;
        //    switch (OrderStatus)
        //    {
        //        case OrderStatus.Pass:
        //            return "审核通过，待发货";
        //        case OrderStatus.ForB1Check:
        //            return "等待B1审核";
        //        case OrderStatus.PartialShipment:
        //            return "已部分发货";
        //        case OrderStatus.CompleteShipment:
        //            return "已完全发货";
        //        case OrderStatus.B1Cancel:
        //            return "已被B1取消";
        //        case OrderStatus.Cancel:
        //            return "已取消";
        //        case OrderStatus.ForFirstBridgeSOFreightConfirm:
        //            return "等待订单运输信息确认";

        //        default:
        //            return "";
        //    }

        //}

        #endregion

        /// <summary>
        /// 通过运输方式ID获取运输方式名称
        /// </summary>
        /// <param name="TransTypeID"></param>
        /// <returns></returns>
        public string GetTransTypeName(int? TransTypeID)
        {
            if (!TransTypeID.HasValue)
                return "";
            string sql = "SELECT  TransTypeName  FROM  TransType WHERE TransTypeID={0} AND LanguageID={1}";

            sql = string.Format(sql, TransTypeID.Value, LanguageID);

            object TransTypeName = DbHelperSQL.GetSingle(sql);

            if (TransTypeName == null)
                return "";

            return TransTypeName.ToString();
        }




        /// <summary>
        ///  过滤HTML代码
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public string checkStr(string html)
        {
            Regex objRegExp = new Regex("<.+?>");
            string strOutput = objRegExp.Replace(html, "");
            strOutput = strOutput.Replace("<", "&lt;");
            strOutput = strOutput.Replace(">", "&gt;");
        
            //把所有空格变为一个空格
            Regex r = new Regex(@"\s+");
            strOutput = r.Replace(strOutput, " ");
            return strOutput.Trim();
        }




        /// <summary>
        /// 过滤用户输入,防止sql注入
        /// </summary>
        /// <returns></returns>
        public void checkStrValid(string  input)
        {

            if (string.IsNullOrEmpty(input))
                return;

            string[] sql = new string[] {"%",";", "'",">","<","=","declare", "select","insert", "update", "delete", "drop", "create", "exec" };
            bool result = false;
            foreach (string str in sql)
                if (input.Contains(str))
                {
                    result = true;
                    break;
                }

            if (result)
                Response.Redirect("/Error.aspx");
        }



        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }


        public PPrice  GetProductBasePrice(int ProductID)
        {
            ProductManager  pm = new ProductManager();

           if (CurrentUserType == UserType.Viewer ||  CurrentUserType == UserType.SelfRegistered)
               return  pm.GetProductBasePrice(ProductID,0);

          
           UserAccount user = CurrentUser as UserAccount;
           return pm.GetProductBasePrice(ProductID, user.CustomerID.Value);
        }


        public string SetInventoryString(object inventory)
        {
            if ((inventory == null) || string.IsNullOrEmpty(inventory.ToString()) || (decimal.Parse(inventory.ToString()) <= 0))
            {
                return GetLangString("UnavailableIvq");
            }
            else
            {
                return GetLangString("AvailableIvq");
            }
        }

        public string GetProductImage(int productID)
        {
            ProductManager pm = new ProductManager();
            Product p = pm.GetModel(productID);

           
            PCategoryManager pcm = new PCategoryManager();


            string filePath = UploadFilePathForProduct + p.ItemCode.Trim() + ".jpg";


            if (System.IO.File.Exists(Server.MapPath(filePath)))
                return filePath;



            return pcm.GetCategoryImage(p.CategoryID.Value);
        }

        public string GetProductList()
        {
            string filePath = UploadFilePathForProduct + LanguageID.ToString() + "_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            StringBuilder sb = new StringBuilder();
            if (System.IO.File.Exists(Server.MapPath(filePath)))
            {
                return GetProductForXml(filePath);
            }
            else
            {
                PCategoryManager categoryManager = new PCategoryManager();
                DataSet ds = categoryManager.GetListAndKwd(LanguageID);
                Hashtable dsMap = new Hashtable();
                Hashtable LstMap = new Hashtable();
                Hashtable CateMap = new Hashtable();
                Hashtable DlMap = new Hashtable();
                Hashtable DivMap = new Hashtable();
                string TmpKey = string.Empty;
                if (ds != null && ds.Tables.Count > 0)
                {
                    DataTable dt = ds.Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        int RowCnt = 0;
                        int DataCnt = 0;
                        int TmpCnt = 0;
                        string CageTmpStr = string.Empty;
                        string TmpStr = string.Empty;
                        string DlStr = string.Empty;
                        string DivStr = string.Empty;
                        StringBuilder S_DIV_STR = null;
                        StringBuilder CateLst = null;
                        StringBuilder TmpLst = null;
                        StringBuilder DlLst = null;
                        StringBuilder DivLst = null;
                        foreach (DataRow dr in dt.Rows)
                        {
                            string key = Convert.ToString(dr["rowID"]);
                            string ParentID = Convert.ToString(dr["ParentID"]);
                            bool IsLeaf = Convert.ToInt32(dr["RowCnt"]) > 0 ? true : false;
                            string CategoryID = Convert.ToString(dr["CategoryID"]);
                            string CategoryName = Convert.ToString(dr["CategoryName"]);
                            if (dsMap.ContainsKey(key))
                            {
                                string val = Convert.ToString(dsMap[key]);
                                if (ParentID == val)
                                {
                                    LstMap.Add(CategoryID, CategoryID);

                                    S_DIV_STR.AppendFormat("<div class=\"product_menu_two_div\">");
                                    if (IsLeaf)
                                        S_DIV_STR.AppendFormat("<h3><a href=\"../Category.aspx?cid={1}\">{0}</a></h3>$[S_CageLst_{1}]", CategoryName, CategoryID);
                                    else
                                        S_DIV_STR.AppendFormat("<h3 class=\"product_menu_h3t\"><a href=\"../Category.aspx?cid={1}\" >{0}</a></h3>", CategoryName, CategoryID);
                                    S_DIV_STR.Append("</div>");
                                    RowCnt++;
                                }
                                if (LstMap.ContainsKey(ParentID))
                                {
                                    if (CageTmpStr != ParentID)
                                    {
                                        if (CateLst != null)
                                        {
                                            CateLst.Append("</ul>");
                                            S_DIV_STR.Replace("$[S_CageLst_" + CageTmpStr + "]", CateLst.ToString());
                                        }
                                        CateLst = new StringBuilder();
                                        CateLst.Append("<ul>");
                                        CageTmpStr = ParentID;
                                    }
                                    if (IsLeaf)
                                    {
                                        CateLst.AppendFormat("<li class=\"product_menu_two_li\"><a href=\"../Category.aspx?cid={1}\">{0}</a>", CategoryName, CategoryID);
                                        CateLst.AppendFormat("$[S_threeLst_{0}]</li>", CategoryID);
                                        CateMap.Add(CategoryID, CategoryName);
                                    }
                                    else
                                    {
                                        CateLst.AppendFormat("<li><a href=\"../Category.aspx?cid={1}\">{0}</a></li>", CategoryName, CategoryID);
                                    }
                                }
                                else
                                {
                                    if (CateLst != null)
                                    {
                                        CateLst.Append("</ul>");
                                        S_DIV_STR.Replace("$[S_CageLst_" + CageTmpStr + "]", CateLst.ToString());
                                    }
                                }
                                if (CateMap.ContainsKey(ParentID))
                                {
                                    if (TmpStr != ParentID)
                                    {
                                        if (TmpLst != null)
                                        {
                                            TmpLst.Append("</div>");
                                            S_DIV_STR.Replace("$[S_threeLst_" + TmpStr + "]", TmpLst.ToString());
                                        }
                                        TmpLst = new StringBuilder();
                                        TmpLst.AppendFormat("<div class=\"product_menu_three\">", CategoryName, CategoryID);
                                        TmpStr = ParentID;
                                        TmpCnt = 0;
                                    }
                                    if (IsLeaf)
                                    {
                                        TmpLst.AppendFormat("<dl><dt class=\"{2}\"><a href=\"../Category.aspx?cid={1}\">{0}</a></dt>", CategoryName, CategoryID, TmpCnt > 0 ? "product_menu_threeon" : "product_menu_threeont");
                                        TmpLst.AppendFormat("$[S_threeDL_{0}]</dl>", CategoryID);
                                        DlMap.Add(CategoryID, CategoryName);
                                        TmpCnt++;
                                    }
                                    else
                                    {
                                        TmpLst.AppendFormat("<dl><dd><a href=\"../Category.aspx?cid={1}\">{0}</a></dd></dl>", CategoryName, CategoryID);
                                    }
                                }
                                else
                                {
                                    if (TmpLst != null)
                                    {
                                        TmpLst.Append("</div>");
                                        S_DIV_STR.Replace("$[S_threeLst_" + TmpStr + "]", TmpLst.ToString());
                                    }
                                }
                                if (DlMap.ContainsKey(ParentID))
                                {
                                    if (DlStr != ParentID)
                                    {
                                        if (DlLst != null)
                                        {
                                            S_DIV_STR.Replace("$[S_threeDL_" + DlStr + "]", DlLst.ToString());
                                        }
                                        DlLst = new StringBuilder();
                                        DlStr = ParentID;
                                    }
                                    if (IsLeaf)
                                    {
                                        DlLst.AppendFormat("<dd class=\"sixmenu\"><a href=\"../Category.aspx?cid={1}\">{0}</a>", CategoryName, CategoryID);
                                        DlLst.AppendFormat("<div class=\"product_menu_four\">$[S_threeDiv_{0}]</div></dd>", CategoryID);
                                        DivMap.Add(CategoryID, CategoryName);
                                    }
                                    else
                                    {
                                        DlLst.AppendFormat("<dd><a href=\"../Category.aspx?cid={1}\">{0}</a></dd>", CategoryName, CategoryID);
                                    }
                                }
                                else
                                {
                                    if (DlLst != null)
                                    {
                                        S_DIV_STR.Replace("$[S_threeDL_" + DlStr + "]", DlLst.ToString());
                                    }
                                }
                                if (DivMap.ContainsKey(ParentID))
                                {
                                    if (DivStr != ParentID)
                                    {
                                        if (DivLst != null)
                                        {
                                            S_DIV_STR.Replace("$[S_threeDiv_" + DivStr + "]", DivLst.ToString());
                                        }
                                        DivLst = new StringBuilder();
                                        DivStr = ParentID;
                                    }
                                    DivLst.AppendFormat("<p><a href=\"../Category.aspx?cid={1}\">{0}</a></p>", CategoryName, CategoryID);
                                }
                                else
                                {
                                    if (DivLst != null)
                                    {
                                        S_DIV_STR.Replace("$[S_threeDiv_" + DivStr + "]", DivLst.ToString());
                                    }
                                }
                            }
                            else
                            {
                                //初始化 Begin
                                if (DataCnt != 0)
                                {
                                    if (CateLst != null)
                                    {
                                        CateLst.Append("</ul>");
                                        S_DIV_STR.Replace("$[S_CageLst_" + CageTmpStr + "]", CateLst.ToString());
                                    }
                                    if (TmpLst != null)
                                    {
                                        TmpLst.Append("</dl></div>");
                                        S_DIV_STR.Replace("$[S_threeLst_" + TmpStr + "]", TmpLst.ToString());
                                    }
                                    if (DlLst != null)
                                    {
                                        S_DIV_STR.Replace("$[S_threeDL_" + DlStr + "]", DlLst.ToString());
                                    }
                                    if (DivLst != null)
                                    {
                                        S_DIV_STR.Replace("$[S_threeDiv_" + DivStr + "]", DivLst.ToString());
                                    }
                                    sb.Replace("$[S_DIV_" + TmpKey + "]", S_DIV_STR.ToString());
                                }
                                RowCnt = 0;
                                S_DIV_STR = new StringBuilder();
                                //End
                                sb.Append("<ul class=\"product_menu_one\">");

                                string HotKeyWords = string.Empty;

                                DataSet Keyds = categoryManager.GetPHotKeyWords(LanguageID, Convert.ToInt32(CategoryID));
                                if (Keyds != null && Keyds.Tables.Count > 0 && Keyds.Tables[0] != null && Keyds.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow Hotdr in Keyds.Tables[0].Rows)
                                    {
                                        HotKeyWords += string.Format("|<a href=\"../Category.aspx?cid={1}\">{0}</a>", Hotdr["CategoryName"], Hotdr["CategoryID"]);
                                    }
                                    HotKeyWords = HotKeyWords.Substring(1);
                                }

                                sb.AppendFormat("<div class=\"product_menu_div\"><h2><a href=\"../Category.aspx?cid={0}\">{1}</a></h2><ul class=\"product_menu_one_ul\">{3}</ul></div>", CategoryID, dr["CategoryName"], key, HotKeyWords);
                                sb.AppendFormat("<div class=\"product_menu_two\"><div class=\"product_menu_two_box\">$[S_DIV_{0}]</div></div>", key);
                                sb.Append("</ul>");
                                dsMap[key] = Convert.ToString(dr["CategoryID"]);
                                DataCnt++;
                                TmpKey = key;
                            }
                        }
                        if (CateLst != null)
                        {
                            CateLst.Append("</ul>");
                            S_DIV_STR.Replace("$[S_CageLst_" + CageTmpStr + "]", CateLst.ToString());
                            CateLst = null;
                        }
                        if (TmpLst != null)
                        {
                            TmpLst.Append("</dl></div>");
                            S_DIV_STR.Replace("$[S_threeLst_" + TmpStr + "]", TmpLst.ToString());
                            TmpLst = null;
                        }
                        if (DlLst != null)
                        {
                            S_DIV_STR.Replace("$[S_threeDL_" + DlStr + "]", DlLst.ToString());
                        }
                        if (DivLst != null)
                        {
                            S_DIV_STR.Replace("$[S_threeDiv_" + DivStr + "]", DivLst.ToString());
                        }
                        sb.Replace("$[S_DIV_" + TmpKey + "]", S_DIV_STR.ToString());
                    }
                }
            }
            return sb.ToString();
        }

        public string GetCategoryListSite(int cid, int brandid)
        {
            PCategoryManager categoryManager = new PCategoryManager();
            DataSet ds = categoryManager.CategoryListSite(cid, LanguageID);
            StringBuilder sb = new StringBuilder();
            int rowCnt = 0;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (rowCnt == 0)
                        sb.AppendFormat("<a href=\"../Category.aspx\">{0}</a>", GetLangString("NewSearch"));
                    else
                        sb.AppendFormat(" — <a href=\"../ChildCategory.aspx?cid={0}&brandid={1}\">{2}</a>", dr["CategoryID"], brandid, dr["CategoryName"]);
                    rowCnt++;
                }
            }
            return sb.ToString();
        }

        private string GetProductForXml(string filePath)
        {
            StringBuilder sb = new StringBuilder();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(Server.MapPath(filePath));//member_update
            StringWriter sw = new StringWriter(sb);
            XmlTextWriter xtw = null;
            try
            {
                xtw = new XmlTextWriter(sw);

                xtw.Formatting = Formatting.None;
                xtw.Indentation = 1;
                xtw.IndentChar = '\t';
                xmlDoc.WriteTo(xtw);
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
            }
            return sb.ToString();
        }

        public   string GetSubString(string str, int length)
        {
            string temp = str;
            int j = 0;
            int k = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
                {
                    j += 2;
                }
                else
                {
                    j += 1;
                }
                if (j <= length)
                {
                    k += 1;
                }
                if (j >= length)
                {
                    return temp.Substring(0, k);
                }
            }
            return temp;
        }

        public string GetSubString(string str, int FLen, int SLen, int LanguageID)
        {
            string rq = string.Empty;
            if (LanguageID == 1)
            {
                if (str.Length > FLen)
                {
                    rq = str.Substring(0, FLen) + "...";
                }
            }
            else
            {
                if (str.Length > SLen)
                {
                    rq = str.Substring(0, SLen) + "...";
                }
            }
            if (string.IsNullOrEmpty(rq))
                rq = str;
            return rq;
        }

    }
}
